-- 全局变量
jzjh_global = {
    mapArea = hrect.create(
            cj.GetCameraBoundMinX() - cj.GetCameraMargin(CAMERA_MARGIN_LEFT),
            cj.GetCameraBoundMinY() - cj.GetCameraMargin(CAMERA_MARGIN_BOTTOM),
            cj.GetCameraBoundMaxX() + cj.GetCameraMargin(CAMERA_MARGIN_RIGHT),
            cj.GetCameraBoundMaxY() + cj.GetCameraMargin(CAMERA_MARGIN_TOP),
            'minmax'
    ),
    test = false,
    base = nil, -- 基地
    wave = 0, -- 波数
    difficulty = 1, -- 难度
    mode = 1, -- 游戏模式
    firstDelay = 20, -- 初始刷怪时间
    frequency = 3.5, -- 几秒出一个怪
    backFrequency = 2, -- 后面几秒出一个怪
    count = 20, -- 每波每条路多少怪
    backCount = 10, -- 后面刷多少怪
    interval = 140, -- 两波之间间隔
    stop = 10, -- 停怪时间
    weather = 0, -- 天象 1-天 12-电
    weatherNpc = nil, -- 天象怪
    weatherExpired = false, -- 天象是否到时
    tasks = {}, -- 任务状态 key是pIndex，value是{mazei = 0, }，0-没接 1-进行中 2-完成 循环任务0->1->0，一次性任务0->1->2
    attr = {}, -- 单位的属性 key是pIndex，value是{gengu= 10, wuxing= 10, danpo = 10, fuyuan = 10, dao = 4, gun = 1, jian = 1, quan = 1, exp=0, lilian=0}
    barrier = {}, -- 闯关数 key是pIndex，value是数值，如闯完天关是4，闯完地关是8
    barrierCounter = {}, -- 每个闯关单位的数量，key是pIndex, value是{xiaoyao = 1, ...}
    pigCounter = {}, -- 杀猪数，key是pIndex, value是数值
    brother = {}, -- 结拜兄弟
    state = { dugu = 0, meichaofeng = 0, husong = 0, mieshen = 0, zhuxin = 0, -- 独孤求败、梅超风、护送张无忌、灭神、蛛心任务状态
              daoExercising = 0, gunExercising = 0, jianExercising = 0, quanExercising = 0, meizhuang = 0,
              jiebai = 0, god = 0 },
    jiebaiIndex = 0, -- 等待结拜的玩家
    killings = {}, -- 杀怪数 key是pIndex, value是{jian = 0, dao = 0, quan = 0, gun = 0, juexue = 0, jinzhong = 0}
    luanmu = {}, -- 鸾暮铠受攻击次数，key是pIndex， value是数值
    itemCooldown = {}, -- 物品技能CD，key是pIndex, value是 {I10R=true}
    weaponTask = {}, -- 是否做过系数任务，key是pIndex, value是{jian = true, dao = true, gun = true, quan = true}
    lilianTask = {}, -- 历练任务，key是pIndex, value是二进制数
    chueTask = {}, -- 除恶任务完成次数
    wushouTask = {}, -- 五兽任务完成次数
    wing = {}, -- 翅膀特效，key是pIndex
    showExp = {}, -- 是否显示江湖阅历，key是pIndex, value是false和true
    heroes = {},
    babies = {},
    beasts = {}, -- 灵兽
    warnSuits = {}, -- 穿的套装 key是pIndex，value是二进制数
    fightingNpc = nil, -- 当前华山比武的NPC
    infoCount = 0, -- 不染凡尘情报数
    buran = false, -- 是否可以进入不染凡尘
    infoFinished = false, -- 不凡尘情报是否完结
    zixia = {}, -- 是否正在释放紫霞功，key是pIndex, value是false和true
    rects = {}, -- 矩形区域列表
    kungfu = {}, -- 武学数量 key是pIndex,value是{juenei = 0, juexue = 0, jianghu = 0}
    canzhang = {}, -- 残章数量 key是pIndex, value是{XXXX=0, YYYY=1}
    skillList = {}, -- 技能列表 key是pIndex, value是{'XXXX', 'YYYY'}
    attackTechs = {}, -- 魔教科技
    bornPlace = {}, -- key是unit,value是{x = XXX, y = YYY}
    basePlayer = cj.Player(7), -- 基地所属的玩家
    attackPlayer = cj.Player(8), -- 进攻怪所属玩家
    trainPlayer = cj.Player(9), -- 练功房所属玩家
    extraPlayer = cj.Player(10), -- 不染凡尘玩家
    creepPlayer = cj.Player(12), -- 野怪玩家
    passivePlayer = cj.Player(15), -- 中立玩家
    leftTrainingGroup = {}, -- 练功房左侧
    rightTrainingGroup = {}, -- 练功房右侧
    aiMap = {}, -- AI字典，key是unit，value是{{orderId='', index='', probability=20}, {orderId='', index='', probability=20}}
    aiTriggerMap = {}, -- key是unit，value是{trigger = t, condition = c}
    attacker = {
        { id = 'nsce' },
        { id = 'ogru' },
        { id = 'nvdl' },
        { id = 'ntka' },
        { id = 'nqbh' },
        { id = 'nmmu' },
        { id = 'nogr' },
        { id = 'ngnb' }, -- 第八波
        { id = 'nfra' },
        { id = 'nrel' },
        { id = 'ncea' },
        { id = 'nkot' },
        { id = 'nanm' },
        { id = 'nbdm' },
        { id = 'ndtt' },
        { id = 'nnht' }, -- 第十六波
        { id = 'nepl' },
        { id = 'npfm' },
        { id = 'nsgn' },
        { id = 'nhdc' },
        { id = 'ninc' },
        { id = 'nthl' },
        { id = 'nwzd' },
        { id = 'nmit' }, -- 第二十四波
        { id = 'nnwq' },
        { id = 'nfpt' },
        { id = 'nrvs' },
        { id = 'nsqe' },
        { id = 'nsrh' },
        { id = 'ntrs' },
        { id = 'ninf' },
        { id = 'nbal' }, -- 第三十二波
    },
    attackBoss = {
        { id = 'nmtw' },
        { id = 'otau' },
        { id = 'hkni' },
        { id = 'Hvwd' },
        { id = 'osw3' },
        { id = 'Otch' },
        { id = 'owar' },
        { id = 'odkt' },
        { id = 'Obla' },
        { id = 'ufro' },
        { id = 'Udea' }, -- 教主
    },
}

--- @private
--- 刷历练怪
local function spawnExperienceCreeps()
    -- 韩小莹
    logic.spawn.instance("o00Q", -2567, -4488, 60)
    -- 全金发
    logic.spawn.instance("o00R", -2072, -5377, 60)
    -- 张阿生
    logic.spawn.instance("o00S", -2423, -5377, 60)
    -- 南希仁
    logic.spawn.instance("o00T", -2940, -4427, 60)
    -- 韩宝驹
    logic.spawn.instance("o00U", -2983, -5435, 60)
    -- 朱聪
    logic.spawn.instance("o00V", -3424, -4594, 60)
    -- 柯镇恶
    logic.spawn.instance("o00W", -3431, -4967, 60)

    -- 金毛狮王
    logic.spawn.instance("o00X", 1930, -4170, 60)
    -- 青翼蝠王
    logic.spawn.instance("o00Y", 1373, -4178, 60)
    -- 白眉鹰王
    logic.spawn.instance("o00Z", 1376, -5449, 60)
    -- 紫衫龙王
    logic.spawn.instance("o010", 825, -5424, 60)
    -- 阳顶天
    logic.spawn.instance("o011", 830, -4313, 60)
end

local function doSpawn()
    jzjh_global.wave = jzjh_global.wave + 1
    if jzjh_global.wave >= 33 then
        echo("|CFFFF0033魔教教主来了，请作好防守准备")
        logic.spawn.finalAttackBoss(CONST_POINT.north.x, CONST_POINT.north.y)
    else
        htime.setTimeout(
                jzjh_global.interval + jzjh_global.stop,
                function(curTimer)
                    htime.delTimer(curTimer)
                    echo("|CFFFF0033魔教进攻势力：第" .. jzjh_global.wave .. "|CFFFF0033波")
                    if jzjh_global.difficulty >= 3 then
                        if math.fmod(jzjh_global.wave, 3) == 1 then
                            jzjh_global.attackTechs[1] = CONST_ATTACK_TECHS[math.random(1, 11)]
                            jzjh_global.attackTechs[2] = 'A1O3'
                            jzjh_global.attackTechs[3] = 'A1O3'
                        elseif math.fmod(jzjh_global.wave, 3) == 2 then
                            jzjh_global.attackTechs[2] = CONST_ATTACK_TECHS[math.random(1, 11)]
                            jzjh_global.attackTechs[3] = 'A1O3'
                        else
                            jzjh_global.attackTechs[3] = CONST_ATTACK_TECHS[math.random(1, 11)]
                        end
                    end
                    echo("|CFFB2FF00魔教当前科技为：" .. hskill.getName(jzjh_global.attackTechs[1]) .. "         " .. hskill.getName(jzjh_global.attackTechs[2]) .. "         " .. hskill.getName(jzjh_global.attackTechs[3]))
                    logic.spawn.attacker(jzjh_global.wave, jzjh_global.count, jzjh_global.frequency, CONST_POINT.east.x, CONST_POINT.east.y)
                    logic.spawn.attacker(jzjh_global.wave, jzjh_global.count, jzjh_global.frequency, CONST_POINT.west.x, CONST_POINT.west.y)
                    logic.spawn.attacker(jzjh_global.wave, jzjh_global.count, jzjh_global.frequency, CONST_POINT.north.x, CONST_POINT.north.y)

                    if math.fmod(jzjh_global.wave, 3) == 0 then
                        htime.setTimeout(100, function(t)
                            htime.delTimer(t)
                            echo("|CFFFF0033魔教派出BOSS前来进攻，请准备防御")
                            logic.spawn.attackBoss(jzjh_global.wave, CONST_POINT.north.x, CONST_POINT.north.y)
                        end)
                    end

                    htime.setTimeout(80, function(t)
                        htime.delTimer(t)
                        if hplayer.qty_current > 1 then
                            echo("|CFFFF0033有一股黑暗势力从背后偷袭过来了")
                            logic.spawn.attacker(jzjh_global.wave, jzjh_global.backCount, jzjh_global.backFrequency, CONST_POINT.south.x, CONST_POINT.south.y)
                        end
                    end)
                    htime.setTimeout(jzjh_global.frequency * jzjh_global.count, function(t)
                        htime.delTimer(t)
                        doSpawn()
                    end)

                end,
                '魔教下次进攻时间')
    end
    jzjh_global.stop = 0
end



-- 选择英雄事件
hevent.onPickHero(function(evtData)
    local p = evtData.triggerPlayer
    local hero = evtData.triggerUnit
    local pIndex = hplayer.index(p)
    jzjh_global.heroes[pIndex] = hero
    hcamera.toXY(p, 0, hhero.bornX, hhero.bornY)

    local newBaby = false
    -- 创建宝宝
    if not jzjh_global.babies[pIndex] then
        newBaby = true
        jzjh_global.babies[pIndex] = hunit.create({
            whichPlayer = p,
            unitId = 'nvul',
            x = hhero.bornX,
            y = hhero.bornY,
        })
    end
    jzjh_global.attr[pIndex] = {
        gengu = 1, wuxing = 1, fuyuan = 1,
        dao = 1, gun = 1, jian = 1, quan = 1,
        daoDamage = 1, gunDamage = 1, jianDamage = 1, quanDamage = 1,
        lilian = 0, juexue = 1, exp = 0, xiulian = 0, --修炼点
        yueli = 0, -- 江湖阅历
    }
    jzjh_global.killings[pIndex] = {
        gun = 0, dao = 0, jian = 0, quan = 0, kuihua = 0, jinzhong = 0, yunv = 0
    }
    jzjh_global.tasks[pIndex] = {}
    jzjh_global.barrierCounter[pIndex] = {}
    jzjh_global.killings[pIndex] = {}
    jzjh_global.itemCooldown[pIndex] = {}
    jzjh_global.weaponTask[pIndex] = {}
    jzjh_global.kungfu[pIndex] = {}
    jzjh_global.canzhang[pIndex] = {}
    jzjh_global.skillList[pIndex] = {}
    jzjh_global.warnSuits[pIndex] = 0
    jzjh_global.barrier[pIndex] = 0
    jzjh_global.luanmu[pIndex] = 0
    jzjh_global.lilianTask[pIndex] = 0
    jzjh_global.chueTask[pIndex] = 0
    jzjh_global.wushouTask[pIndex] = 0

    jzjh_global.showExp[pIndex] = true
    jzjh_global.kungfu[pIndex] = {
        juexue = 0, juenei = 0, jianghu = 0
    }
    hevent.onItemUsed(hero, logic.item.used)
    if newBaby then
        hevent.onItemUsed(jzjh_global.babies[pIndex], logic.item.used)
    end

    local trig = cj.CreateTrigger()
    cj.TriggerRegisterUnitEvent(trig, hero, EVENT_UNIT_PICKUP_ITEM)
    if newBaby then
        cj.TriggerRegisterUnitEvent(trig, jzjh_global.babies[pIndex], EVENT_UNIT_PICKUP_ITEM)
    end
    cj.TriggerAddCondition(trig, cj.Condition(logic.item.get))

    trig = cj.CreateTrigger()
    cj.TriggerRegisterUnitEvent(trig, hero, EVENT_UNIT_DROP_ITEM)
    if newBaby then
        cj.TriggerRegisterUnitEvent(trig, jzjh_global.babies[pIndex], EVENT_UNIT_DROP_ITEM)
    end
    cj.TriggerAddCondition(trig, cj.Condition(logic.item.drop))

    hevent.onSkillEffect(hero, logic.skill.effect)
    if newBaby then
        hevent.onSkillEffect(jzjh_global.babies[pIndex], logic.skill.effect)
    end

    hevent.onSkillAdd(hero, function(evt)
        local triggerUnit = evt.triggerUnit
        local skillId = evt.skillId
        table.insert(jzjh_global.skillList[pIndex], skillId)
        print_mb("玩家" .. pIndex .. "学习了技能" .. skillId)
    end)

    hevent.onSkillDelete(hero, function(evt)
        local triggerUnit = evt.triggerUnit
        local skillId = evt.skillId
        table.delete(skillId, jzjh_global.skillList[pIndex])
    end)

    -- 英雄死亡复活
    hevent.onDead(hero, function(evt)
        local u = evt.triggerUnit
        local killer = evt.killer
        local killerId = hunit.getId(killer)
        -- 玩家英雄死后复活
        if his.hero(u) and his.playerSite(hunit.getOwner(u)) then
            local heroP = hunit.getOwner(u)
            htime.setTimeout(15, function(curTimer)
                htime.delTimer(curTimer)
                cj.ReviveHero(u, hhero.bornX, hhero.bornY, true)
                hcamera.toXY(heroP, 0, hhero.bornX, hhero.bornY)
            end, cj.GetHeroProperName(u) .. "重出江湖")
            if jzjh_global.weather == 2 then
                if cj.GetHeroInt(u, false) > 100 then
                    cj.SetHeroInt(u, cj.GetHeroInt(u, false) - 100, true)
                end
                if cj.GetHeroAgi(u, false) > 100 then
                    cj.SetHeroAgi(u, cj.GetHeroAgi(u, false) - 100, true)
                end
                if cj.GetHeroStr(u, false) > 100 then
                    cj.SetHeroStr(u, cj.GetHeroStr(u, false) - 100, true)
                end
                echo("|cFFCC0000受天象影响，本次死亡扣除了英雄100点全属性|r", heroP)
            end
        end

        if killerId == 'Hart' then
            if jzjh_global.tasks[pIndex].dugu == 1 then
                jzjh_global.tasks[pIndex].dugu = 0
                echo("|CFF00FFCC很好，你开始领悟了武学的精义了。那么我再给你点化点化。\n世人皆谓手中无剑，心中有剑为剑法精髓，须不知手中无剑，心中也无剑才是武学最高境界。人们求神兵利器，不若有招在心，有招在心，不若随心而欲。", p)
                echo("|CFF00FFCC完成任务：独孤前辈的点化，获得剑系数+3", p)
                jzjh_global.attr[pIndex].jian = jzjh_global.attr[pIndex].jian + 3
                jzjh_global.weaponTask[pIndex].jian = true
                jzjh_global.state.dugu = 1
                htime.setTimeout(1800, function(curTimer)
                    htime.delTimer(curTimer)
                    jzjh_global.state.dugu = 0
                end)
            end
        end
    end)
end)

-- 玩家聊天事件
for i = 1, bj_MAX_PLAYERS, 1 do
    hevent.onChat(hplayer.players[i], '', false, logic.chat)

    local trig = cj.CreateTrigger()
    cj.TriggerRegisterPlayerStateEvent(trig, hplayer.players[i], PLAYER_STATE_RESOURCE_GOLD, GREATER_THAN_OR_EQUAL, 500000.00)
    cj.TriggerAddCondition(trig, cj.Condition(function()
        hplayer.subGold(hplayer.players[i], 500000)
        hplayer.addLumber(hplayer.players[i], 50)
        echo("|CFFFF00CC有玩家铜币超过50W，自动转换成50金币")
    end))

    hevent.onSelection(hplayer.players[i], 1, logic.hint)

    trig = cj.CreateTrigger()
    cj.TriggerRegisterPlayerEvent(trig, hplayer.players[i], EVENT_PLAYER_ARROW_LEFT_DOWN)
    cj.TriggerAddAction(trig, logic.keyDown.left)

    trig = cj.CreateTrigger()
    cj.TriggerRegisterPlayerEvent(trig, hplayer.players[i], EVENT_PLAYER_ARROW_RIGHT_DOWN)
    cj.TriggerAddAction(trig, logic.keyDown.right)

    trig = cj.CreateTrigger()
    cj.TriggerRegisterPlayerEvent(trig, hplayer.players[i], EVENT_PLAYER_ARROW_UP_DOWN)
    cj.TriggerAddAction(trig, logic.keyDown.up)

    trig = cj.CreateTrigger()
    cj.TriggerRegisterPlayerEvent(trig, hplayer.players[i], EVENT_PLAYER_ARROW_DOWN_DOWN)
    cj.TriggerAddAction(trig, logic.keyDown.down)
end




-- 延时游戏时间0.1秒，确保已进入游戏
local startTrigger = cj.CreateTrigger()
cj.TriggerRegisterTimerEvent(startTrigger, 0.1, false)
cj.TriggerAddAction(
        startTrigger,
        function()
            logic.init()
            -- 开启F9提示
            hLuaF9({ "all" })

            cj.DisableTrigger(startTrigger)
            cj.DestroyTrigger(startTrigger)

            cj.SetPlayerState(jzjh_global.creepPlayer, PLAYER_STATE_NO_CREEP_SLEEP, 1)
            local g = hgroup.createByPlayers(jzjh_global.creepPlayer, nil)
            hgroup.loop(g, function(enumUnit)
                cj.UnitWakeUp(enumUnit)
            end, true)

            -- 设置英雄出生点
            hhero.setBornXY(-100, 2970)

            -- 选择英雄
            hhero.buildSelector(
                    {
                        heroes = { 'E000', 'E001', 'E002', 'O000', 'O001', 'O002', 'U000', 'O005', 'H00F', 'E00N', 'E00P', 'E00O', 'H000', 'H009', 'H00A', 'H001' },
                        buildX = -2068,
                        buildY = 15316,
                        buildDistanceX = 200,
                        buildDistanceY = 200,
                        buildRowQty = 6,
                        during = -1,
                        type = "click",
                        heroInfos = CONST_HERO_MAP
                    }
            )

            -- 刷怪
            doSpawn()

            -- 刷历练怪
            spawnExperienceCreeps()


        end
)

cj.TimerStart(cj.CreateTimer(), 1.00, true, logic.tick)
